package com.mz361.stdapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mz361.common.utils.RedisUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.modules.system.domain.CMember;
import com.mz361.modules.system.service.CMemberService;
import com.mz361.stdapi.domain.StandardData;
import com.mz361.stdapi.domain.StandardTable;
import com.mz361.stdapi.service.StandardProfileService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


/**
 * @author niceale
 * @ date 2024/04/26
 */
@Service
@Slf4j
public class StandardProfileServiceImpl implements StandardProfileService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    private CMemberService cMemberService;

    /**
     * 标准概要
     *
     * @ param standardNo
     * @ return
     */
    @Override
    public StandardData standardProfile(String userId, String standardNo) {
        standardNo = standardNo.replace("&nbsp;", " ");
        StandardData standardData = new StandardData();
        // 判断缓存中是否已存在
        if (redisUtil.hexists("STANDARD:NO", standardNo)) {
            standardData = JSONObject.parseObject(redisUtil.hGet("STANDARD:NO", standardNo), StandardData.class);
        } else {
            StandardTable standardTable = getStandardTable(standardNo);
            if (standardTable != null) {
                standardData.setTitle(standardTable.getFn_A301());//中文名称
                //标准概要排名记录
                redisUtil.incrementKeyword("SORT:STANDARDINFO:TITLE", standardNo + "｜" + standardTable.getFn_A301());
                String enTitle = standardTable.getFn_A302();
                standardData.setEnTitle(enTitle);//英文名称
                standardData.setStandardNo(standardTable.getFn_A100());//标准号
                standardData.setStandardStatus(standardTable.getFn_StandStatus());//标准状态

                String ownerDept = standardTable.getFn_ownerDept();
                String impDate = standardTable.getFn_A205();
                String pubTime = standardTable.getFn_ModiDate();
                standardData.setOwnerDept(ownerDept);//标准简介
                standardData.setPubTime(pubTime != null && StringUtil.isContans(pubTime, " ") ? pubTime.split(" ")[0] : pubTime);//发布时间
                standardData.setImpDate(impDate != null && StringUtil.isContans(impDate, " ") ? impDate.split(" ")[0] : impDate);//实施时间
                standardData.setLanguage(standardTable.getFn_Language());//出版语种
                standardData.setIcs(standardTable.getFn_A404());//标准ics号
                standardData.setCcs(standardTable.getFn_A825());//中标分类号
                standardData.setRepalceStandard(standardTable.getFn_A461());//替代以下标准
                standardData.setRepalcedStandard(standardTable.getFn_A462());//被以下标准替代
                standardData.setReferStandard(standardTable.getFn_ReferStandNo());//引用标准
                standardData.setAdoptStandard(standardTable.getFn_AdoptNo());//采用标准
                standardData.setPageNum(standardTable.getFn_A305());//页数
                standardData.setWordNum(standardTable.getFn_wordCount());//字数
                standardData.setFormat(standardTable.getFn_format());//开本
                standardData.setDraftsUnit(standardTable.getFn_draftsDept());//起草单位
                standardData.setDraftsMan(standardTable.getFn_draftsMan());//起草人
                standardData.setFocalUnit(standardTable.getFn_CommitteeDesc());//归口单位
                standardData.setSueDept(standardTable.getFn_SueDepart());//提出部门
                standardData.setPubDept(standardTable.getFn_publish());//发布部门
                if (standardTable.getFn_price() != null) {
                    standardData.setPrice(standardTable.getFn_price());
                } else {
                    standardData.setPrice(35.0);
                }
                if (standardTable.getFn_StandType().equals("GB") && StringUtil.isEmpty(standardTable.getFn_AdoptNo())) {
                    standardData.setFree(true);
                }
                redisUtil.hSet("STANDARD:NO", standardNo, JSONObject.toJSONString(standardData));

            }
        }
        if (StringUtil.notEmpty(userId)) {//   如果是注册用户判断此用户的套餐是否已使用完
            checkDownLoadAndReadOnline(userId, standardData);
        }
        return standardData;

    }

    @Override
    public StandardTable getStandardTable(String standardNo) {
        StandardTable standardTable = null;
        NativeSearchQueryBuilder query = new NativeSearchQueryBuilder();
        query.withQuery(QueryBuilders.matchPhraseQuery("fn_A100", standardNo));
        ElasticsearchRestTemplate restTemplate = new ElasticsearchRestTemplate(restHighLevelClient);
        SearchHits<StandardTable> hits = restTemplate.search(query.build(), StandardTable.class);
        for (SearchHit<StandardTable> searchHit : hits.getSearchHits()) {
            standardTable = searchHit.getContent();
            break;
        }
        return standardTable;
    }

    /**
     * 检测用户套餐情况
     *
     * @ param userId
     * @ param standardData
     */

    public void checkDownLoadAndReadOnline(String userId, StandardData standardData) {
        CMember cMember = cMemberService.getById(Long.valueOf(userId));
        String redisStr = "";
        if ("1".equals(cMember.getType())) {// 个人用户
            redisStr = "P:" + cMember.getId();
        } else if ("2".equals(cMember.getType())) {//企业用户
            redisStr = "Q:" + cMember.getCompanyId();
        }
        if (redisUtil.hexists("DOWNLOAD:ZERO", redisStr)) {
            standardData.setDownloadStatus(false);
        }
        if (redisUtil.hexists("READ:ZERO", redisStr)) {
            standardData.setPrintStatus(false);
        }
    }

}
